﻿#include <QWidget>
#include <QTextCodec>
#include <QPainter>
#include <QAction>
#include <QMessageBox>
#include <QBitmap>
#include <QJsonObject>
#include <QJsonDocument>
#include "userlogin.h"
#include "ui_userlogin.h"
UserLogin* UserLogin::_instance=nullptr;
UserLogin::UserLogin(QDialog* parent) :
    QDialog(parent),
    ui(new Ui::UserLogin)
{
    //sqlInit();
    userName = "";
    ui->setupUi(this);


    this->setWindowFlags(Qt::FramelessWindowHint | Qt::SplashScreen);
    this->setWindowTitle("登录");
    tryCount = 0;

    QRegExp regExp("^[^(\\s|\u4e00-\u9fa5)]+$");
    lineEdit = new QLineEdit(this);
    QAction *userAction = new QAction(lineEdit);
    userAction->setIcon(QIcon("./image/用户.png"));
    lineEdit->addAction(userAction, QLineEdit::LeadingPosition);
    lineEdit->setPlaceholderText("用户名");
    lineEdit->setValidator(new QRegExpValidator(regExp,this));
    lineEdit->setPlaceholderText("提示信息");
    ui->comboBox_count->setLineEdit(lineEdit);


    auto clearAction = new QAction(this);
    clearAction->setIcon(QApplication::style()->standardIcon(QStyle::SP_DialogResetButton));
    lineEdit->addAction(clearAction, QLineEdit::TrailingPosition);
    connect(clearAction,&QAction::triggered, [=](){ clearCount();});

    QAction *passwordAction = new QAction(ui->PasswordLineEdit);
    passwordAction->setIcon(QIcon("./image/密码.png"));
    ui->PasswordLineEdit->addAction(passwordAction, QLineEdit::LeadingPosition);
    ui->PasswordLineEdit->setPlaceholderText("密码");
    ui->PasswordLineEdit->setValidator(new QRegExpValidator(regExp,this));

    //添加connect
    connect(ui->LoginBtn,&QPushButton::clicked,this,&UserLogin::login);
    connect(ui->BtnMenuClose,&QPushButton::clicked,this,&UserLogin::QuitAndExit);
    this->installEventFilter(this);

    connect(this,&UserLogin::s_loadSuccess,  this, &UserLogin::loadSuccess);
    connect(this,&UserLogin::s_loadFail,     this, &UserLogin::loadFail );
    connect(this,&UserLogin::s_registSuccess,this, &UserLogin::registSuccess);
    connect(this,&UserLogin::s_registFail,   this, &UserLogin::registFail);
    connect(ui->RegistBtn,&QPushButton::clicked,this,&UserLogin::RegistBtn_clicked);
    initUserInfo();
    clearCount();
}

UserLogin::~UserLogin()
{
    delete ui;
}

void UserLogin::login()
{
    if(m_status!=Free)
    {
        QMessageBox::information(this,"errir","正在登录中");
        return;
    }
    QString count=ui->comboBox_count->currentText();
    if (count.isEmpty()) {
        QMessageBox::information(this,"error","用户名不能为空！");
        return;
    }
    QString password=ui->PasswordLineEdit->text();
    if(ui->PasswordLineEdit->text().isEmpty()) {
        QMessageBox::information(this,"error","密码不能为空！");
        return;
    }

    m_count=count;
    m_pasw=password;

    QJsonObject json;
    json.insert("type",QString("Load"));
    json.insert("count",count);
    json.insert("password",password);
    QJsonDocument document;
    document.setObject(json);
    QByteArray bytearray = document.toJson(QJsonDocument::Compact);
    sock_client->writeQString(bytearray);
    m_status=Loading;
}

void UserLogin::QuitAndExit()
{
    close();
    //exit(0);
}

bool UserLogin::eventFilter(QObject *obj, QEvent *evt)
{
    static QPoint mousePoint;
    static bool mousePressed = false;

    QMouseEvent *event = static_cast<QMouseEvent *>(evt);
    if (event->type() == QEvent::MouseButtonPress) {
        if (event->button() == Qt::LeftButton) {
            mousePressed = true;
            mousePoint = event->globalPos() - this->pos();
            return true;
        }
    }
    else if (event->type() == QEvent::MouseButtonRelease) {
        mousePressed = false;
        return true;
    }
    else if (event->type() == QEvent::MouseMove) {
        if (mousePressed && (event->buttons() && Qt::LeftButton)) {
            this->move(event->globalPos() - mousePoint);
            return true;
        }
    }

    return QWidget::eventFilter(obj, evt);
}

void UserLogin::paintEvent(QPaintEvent *)
{
    QPainter p;
    p.begin(this);
    p.drawPixmap(0, 0, width(), height(), QPixmap("./image/bj.png"));
    p.end();
}

void UserLogin::initUserInfo()
{
    string now_loading=lineEdit->text().toStdString();
    ui->comboBox_count->clear();
    m_vec.clear();

    m_vec  =SqlDb::getInstance()->getAllClientInfo("select *from user");
    for(auto node:m_vec)
    {
        ui->comboBox_count->addItem(node.count.c_str());
        if(now_loading==node.count)
        {
            if(node.password != "--")
            {
                lineEdit->setText(node.password.c_str());
                ui->checkBox->setChecked(true);
            }
        }
    }
}

void UserLogin::clearCount()
{
    lineEdit->clear();
    ui->checkBox->setChecked(false);
    ui->PasswordLineEdit->clear();
    loadPic("./image/2.png");
}

void UserLogin::on_comboBox_count_activated(const QString &arg1)
{
    if(m_vec.size()>0){
        ui->PasswordLineEdit->clear();
    }
    for(auto it: m_vec)
    {
        if(it.count==arg1.toStdString())
        {
            if(it.password != "--") {
                ui->PasswordLineEdit->setText(it.password.c_str());
                ui->checkBox->setChecked(true);
            }
            else {
                ui->PasswordLineEdit->clear();
                 ui->checkBox->setChecked(false);
            }
            loadPic(it.pic);
        }
    }
}


QPixmap UserLogin::PixmapToRound(QPixmap &src, int radius)
{
    if (src.isNull()) {
        return QPixmap();
    }

    QSize size(2*radius, 2*radius);
    QBitmap mask(size);
    QPainter painter(&mask);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setRenderHint(QPainter::SmoothPixmapTransform);
    painter.fillRect(0, 0, size.width(), size.height(), Qt::white);
    painter.setBrush(QColor(0, 0, 0));
    painter.drawRoundedRect(0, 0, size.width(), size.height(), 99, 99);

    QPixmap image = src.scaled(size);
    image.setMask(mask);
    return image;
}

void UserLogin::loadPic(std::string pic_path)
{
    QPixmap pixmap_userIcon;
    pixmap_userIcon.load(pic_path.c_str());
    //将图片剪裁压缩成20x20大小的图
    QPixmap fitpixmap_userIcon=pixmap_userIcon.scaled(40, 40,
                                                      Qt::IgnoreAspectRatio,
                                                      Qt::SmoothTransformation);
    fitpixmap_userIcon = PixmapToRound(fitpixmap_userIcon,10);
    ui->label_icon->setPixmap(fitpixmap_userIcon);
}

bool UserLogin::checkString(QString check_info)
{
    for(auto it:check_info)
    {
        if((it >= 'A') && (it <= 'Z')||
           (it >= 'a') && (it <= 'z')||
           (it >= '0') && (it <= '9'))
        {
            continue;
        }
        else
        {
            return false;
        }
    }
    return true;
}

void UserLogin::RegistBtn_clicked()
{
    if(m_status!=Free)
    {
        QMessageBox::information(this,"暂时无法注册,稍等","*--*");
        return;
    }
    QString count=this->lineEdit->text();
    QString password=ui->PasswordLineEdit->text();
    if(checkString(count)==false || checkString(password)==false)
    {
        QMessageBox::information(this,"error","同户名密码只能为数字0-9 || a-z || A-Z");
        return;
    }

    QJsonObject json;
    json.insert("type",QString("Register"));
    json.insert("count",count);
    json.insert("password",password);
    QJsonDocument document;
    document.setObject(json);
    QByteArray bytearray = document.toJson(QJsonDocument::Compact);
    sock_client->writeQString(bytearray);
    m_status=Registing;
}

void UserLogin::saveUserInfo(QString count,QString password)
{
    UserInfo info;
    info.count   =count.toStdString();
    if(ui->checkBox->checkState()==Qt::Unchecked)
    {
        info.password="--";
    }
    else {
        info.password=password.toStdString();
    }

    QString insertValue=QString("insert into user(user_name, cipher) values('%1', '%2')")
            .arg(info.count.c_str()).arg(info.password.c_str());
    if(SqlDb::getInstance()->doSql(insertValue.toStdString()))
    {
        m_vec.push_back(info);
        ui->comboBox_count->addItem(count);
    }
    else
    {
        QString updateVal=QString("update user set user_name='%1',cipher='%2' where user_name ='%3'")
                .arg(info.count.c_str())
                .arg(info.password.c_str()).arg(info.count.c_str());
        if(SqlDb::getInstance()->doSql(updateVal.toStdString()))
        {
            for(auto &node:m_vec)
            {
                if(node.count==info.count)
                {
                    node.password=info.password;
                    break;
                }
            }
            ui->comboBox_count->addItem(count);
        }
    }

    loadPic(info.pic);
}

void UserLogin::loadSuccess()
{
    m_status=Free;
    saveUserInfo(m_count,m_pasw);
    QMessageBox::information(this,"success","登录成功");
    this->hide();
    m_game->show();

    clearCount();
}

void UserLogin::loadFail()
{
    m_status=Free;
    QMessageBox::information(this,"fail","账号密码错误");
}

void UserLogin::registSuccess()
{
    m_status=Free;
    //saveUserInfo(m_count,m_pasw);
    QMessageBox::information(this,"scucess","注册成功");
}

void UserLogin::registFail()
{
    m_status=Free;
    QMessageBox::information(this,"fail","账号重复");
}

void UserLogin::setSocketClient(shared_ptr<SockClient> tcp_com)
{
    sock_client=tcp_com;
}

void UserLogin::closeEvent ( QCloseEvent * e )
{
    if( QMessageBox::question(this,
                             tr("Quit"),
                             tr("Are you sure to quit this application?"),
                              QMessageBox::Yes, QMessageBox::No )
                   == QMessageBox::Yes){
        e->accept();//不会将事件传递给组件的父组件
        exit(0);
    }
    else
      e->ignore();
}

void UserLogin::setGame(ChessShow *game)
{
    m_game=game;
}
